<?php

/**
 * Created by PhpStorm.
 * User: yulongyang
 * Date: 2017/3/1
 * Time: 下午1:07
 */
class myLog
{
    private $logStr = '';
    const LOG_LEVEL_ERROR = 1;
    const LOG_LEVEL_WARNING = 2;
    const LOG_LEVEL_NOTICE = 3;
    const LOG_FILE = "PHP_Log_%s.log";
    
    public function __construct()
    {
        
    }
    
    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        if ($this->logStr != '') {
            $file = sprintf(self::LOG_FILE, date("Y-m-d H:i:s"));
            file_put_contents($file, $this->logStr, FILE_APPEND);
        }
    }
    
    /**
     *私有方法, 给类内部自己调用
     */
    private function log($string, $level)
    {
        switch ($level) {
            case self::LOG_LEVEL_ERROR:
                $this->logStr .= "[".date('Y-m-d H:i:s')."]"." ERROR ".$string ."\n";
                break;
            case self::LOG_LEVEL_WARNING:
                $this->logStr .= "[".date('Y-m-d H:i:s')."]"." WARNING ".$string ."\n";
                break;
            case self::LOG_LEVEL_NOTICE:
                $this->logStr .= "[".date('Y-m-d H:i:s')."]"." NOTICE ".$string ."\n";
                break;
        }
    }
    
    public function notice($string)
    {
        $this->log($string, self::LOG_LEVEL_NOTICE);
    }
    
    public function error($string)
    {
        $this->log($string, self::LOG_LEVEL_ERROR);
    }
    
    public function warn($string)
    {
        $this->log($string, self::LOG_LEVEL_WARNING);
    }
}

//$log = new myLog();
//$i = 0;
//for ($i; $i < 10; $i++) {
//    $log->notice("test $i");
//    echo $i ."\r\n";
//    sleep(10);
//}
//$log->notice("test 1");
//set_exception_handler(), set_error_handler() 改写自定义的错误类

//set_exception_handler('exception_handle');

/**
 * 自定义异常处理函数
 */
//function exception_handle($exception) {
//    $log = new myLog();
//    $message = $exception->getMessage();
//    $log->notice($message);
//}
//
//throw new Exception('测试自定义的错误处理类');

set_error_handler('error_handle');
function error_handle($errno, $errstr, $errfile, $errline) {
    $log = new myLog();
    switch ($errno) {
        case E_USER_ERROR:
            $log->error($errstr);
            break;
        case E_USER_WARNING:
            $log->warn($errstr);
            break;
        case E_USER_NOTICE:
            $log->notice($errstr);
            break;
    }
}

trigger_error('使用自己的的 trigger_error 函数测试自定义错误类-E_USER_WARNING', E_USER_WARNING);
trigger_error('使用自己的的 trigger_error 函数测试自定义错误类-E_USER_ERROR', E_USER_ERROR);
trigger_error('使用自己的的 trigger_error 函数测试自定义错误类-E_USER_ERROR', E_USER_NOTICE);